/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.QuickTips.init();
var _pageSize = 20;
var _pageSizeSmall = 10;

var fieldName = ['id', 'name', 'x', 'y', 'h', 'pointTypeId', 'pointType', 'pointType2Id', 'pointType2', 'voltageLevelId', 'voltageLevelName', 'status', 'note', 'updateTime',
    'creatTime', 'orgCode', 'deptId', 'fromId', 'lowerLimit', 'upperLimit', 'pointArea', 'pointPosition', 'userName', 'publicName', 'deviceId', 'code', 'company', 'installSite',
    'manufactoryName', 'model', 'commTypeName', 'mobileNo', 'ip', 'terminalNo', 'installTime', 'checkTime', 'effectTime', 'stopTime', 'stopReason', 'expireTime', 'produceTime', 'port',
    'uniqueCode', 'zbm', 'adminAreaCode', 'channel', 'runTime', 'subCompany', 'shortName', 'stationVoltageLevel', 'realName', 'deviceType', 'lastHBTime', 'lastUploadTime', 'lastTalk', 'uploadMsg','uploadTime'];
var fieldLabel = ['ID', '监测点名称', '经度', '纬度', '高度', '监测点类型ID（类别1）', '监测点类型(类别1)', '电网类型ID（类别2）', '电网类别（类别2）', '电压等级ID', '电压等级', '状态',
    '备注', '记录的更新时间', '记录的创建时间', '机构编码', '所属部门编码', '上级监测点', '电压下限', '电压上限', '用户名称', '公变名称', '设备ID', '监测点编码', '供电局', '安装位置',
    '生产厂家', '装置型号', '通信方式', '通信卡号', 'IP地址', '终端编号', '安装日期', '校验日期', '生效日期', '停用日期', '停用原因', '有效期', '出厂日期', '端口', '唯一码', '组编码', '行政区域码',
    '通道', '投运日期', '部门分县局', '供电所', '所属变电站电压等级', '管理人员', '装置类别', '在线离线', '上报观测', '启用停用', '上次心跳时间', '上次上传数据时间', '最后通信时间'];

var saveServlet = basePath + 'servlet/system/PointSave';
var loadServlet = basePath + 'servlet/system/PointLoad';
var deleteServlet = basePath + 'servlet/system/PointDel';
var unbindServlet = basePath + 'servlet/point/PointUnbind';

var deviceSaveServlet = basePath + 'servlet/system/DeviceSave';

var theme = '装置上报';

var _title = currentOrgName + theme + '管理';

var now = new Date();
var cmd = 'report';
var uploadType = 1;


function getPointNames(rs, n) {
    var jsonData = "";
    for (var i = 0, len = rs.length; i < len; i++) {
        var ss = rs[i].get(n);
        if (i === 0) {
            jsonData = jsonData + ss;
        }
        else {
            jsonData = jsonData + "," + ss;
        }
    }
    return jsonData;
}


var reportStatusStore = new Ext.data.ArrayStore({
    fields: ['id', 'reportStatus']
});
var reportStatusCombo = {
    name: 'reportStatus',
    id: 'ReportStatusCombo',
    xtype: 'combo',
    fieldLabel: '上报状态',
    width: 180,
    triggerAction: 'all',
    //emptyText: '请选择测点地域...',
    editable: false,
    store: reportStatusStore,
    displayField: 'reportStatus',
    valueField: 'id',
    hiddenName: 'reportStatusId',
    mode: 'local',
    value: 0
};

var reportForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'ReportForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesReport',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    diable: true,
                    fieldLabel: '所选监测点',
                    allowBlank: false,
                    blankText: '监测点名称必须填写'
                }
                , reportStatusCombo
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winReport.hide();
                                store.reload();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        submitConfig.params.pointIds = ids.pointIds;
                        submitConfig.params.cmd = cmd;
                        submitConfig.params.type = uploadType;
                        Ext.getCmp('ReportForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winReport.hide();
                    }
                }]
        }
);
var winReport = new Ext.Window({
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [reportForm]
});

function report() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择,需要先选择才能进行操作");
    } else {
        //var r = checkboxSel.getSelected();
        var pointNames = getPointNames(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesReport').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        cmd = 'report';
        reportStatusStore.loadData([[0, '观测'], [1, '上报']]);
        Ext.getCmp('ReportStatusCombo').setValue(0);
        winReport.show();
    }
}


function upload() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能进行操作");
    } else {
        var pointNames = getPointNames(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesReport').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        uploadType = this.type;
        cmd = 'upload';
        reportStatusStore.loadData([[0, '不上报'], [1, '上报']]);
        Ext.getCmp('ReportStatusCombo').setValue(0);
        winReport.show();
    }
}

var uploadForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'UploadForm',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: '../../../servlet/task/TaskUploadSave',
            items: [{
                    name: 'pointNames',
                    xtype: 'textarea',
                    id: 'PointNamesUpload',
                    width: 180,
                    height: 200,
                    readOnly: true,
                    disable: true,
                    fieldLabel: '所选监测点'
                }
            ],
            buttons: [{
                    text: '确定',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                winUpload.hide();
                                Ext.Msg.alert("系统提示", action.result.msg);
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('系统提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('系统提示', action.result.msg);
                                }
                            },
                            params: {cmd: 'createPTask'}
                        };
                        //alert(checkboxSel.getSelections().length);
                        var token1 = new Date().getTime();
                        submitConfig.params.token = token;
                        submitConfig.params.token1 = token1;
                        var ids = getIds(checkboxSel.getSelections());
                        submitConfig.params.pointIds = ids.pointIds;
                        Ext.getCmp('UploadForm').getForm().submit(submitConfig);
                    }
                }, {
                    text: '取消',
                    handler: function() {
                        winUpload.hide();
                    }
                }]
        }
);
var winUpload = new Ext.Window({
    title: '监测点数据上传',
    layout: 'form',
    width: 400,
    autoHeight: true,
    closeAction: 'hide',
    items: [uploadForm]
});


function taskUpload() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，请选择需要上传的监测点");
    } else {
        var rs = checkboxSel.getSelections();

        for (var i = 0; i < rs.length; i++) {
            var status = rs[i].get("status");
            if (status) {
                status = parseInt(status);
                status = Math.floor(status % 1000 / 100);
                if (status === 0) {
                    Ext.Msg.alert("系统提示", "存在不上报测点");
                    return;
                }
            }
        }
        var pointNames = getFields(checkboxSel.getSelections(), 'name');
        Ext.getCmp('PointNamesUpload').setValue(pointNames);
        //Ext.getCmp('ReportStatusCombo').setValue();
        winUpload.show();
    }
}


var winUploadMsg = new Ext.Window({
    title: '上传反馈信息',
    modal:true,
    layout: 'fit',
    width: 400,
    height: 300,
    closeAction: 'hide',
    items: [
        {
            id:"MsgPanel",
            xtype:'panel',
            html: 'Thank you for filling out our form!'
        }
    ]
});

var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {
    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
                , baseParams: {start: 0, limit: _pageSize, cmd: "run"}
        , autoLoad: true
    });

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        autoExpandColumn: fieldLabel[12],
        columns: [
            checkboxSel,
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: '监测点编码', width: 100, sortable: true, dataIndex: 'code'},
            {header: '供电局', width: 100, sortable: true, dataIndex: 'company'},
            {header: '部门分县局', width: 100, sortable: true, dataIndex: 'subCompany'},
            {header: '监测点类型', width: 100, sortable: true, dataIndex: 'pointType'},
            {header: '电网类型', width: 100, sortable: true, dataIndex: 'pointType2'},
            {header: '监测点名称', width: 100, sortable: true, dataIndex: 'name'},
            {header: '启用停用', width: 80, sortable: true, dataIndex: 'status', renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    if (value % 10 === 1) {
                        return '启用';
                    } else {
                        return '停用';
                    }
                }
            },
            {header: '上报观测', width: 80, sortable: true, dataIndex: 'status', renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                    if (value % 100 >= 10) {
                        return '上报';
                    } else {
                        return '观测';
                    }
                }
            },
            {header: '上次心跳时间', width: 80, sortable: true, dataIndex: 'lastHBTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '上次上传数据时间', width: 80, sortable: true, dataIndex: 'lastUploadTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '最后通信时间', width: 80, sortable: true, dataIndex: 'lastTalk', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '电压等级', width: 100, sortable: true, dataIndex: 'voltageLevelName', align: 'right', hidden: true},
            {header: '电压上限', width: 100, sortable: true, dataIndex: 'upperLimit', xtype: 'numbercolumn', format: '0.00', align: 'right', hidden: true},
            {header: '电压下限', width: 100, sortable: true, dataIndex: 'lowerLimit', xtype: 'numbercolumn', format: '0.00', align: 'right', hidden: true},
            {header: '测点地域', width: 100, sortable: true, dataIndex: 'pointArea', hidden: true},
            {header: '测点位置', width: 100, sortable: true, dataIndex: 'pointPosition', hidden: true},
            {header: '供电所', width: 100, sortable: true, dataIndex: 'shortName', hidden: true},
            {header: '所属变电站电压等级', width: 120, sortable: true, dataIndex: 'stationVoltageLevel', hidden: true},
            {header: '用户名称', width: 120, sortable: true, dataIndex: 'userName', hidden: true},
            {header: '公变名称', width: 120, sortable: true, dataIndex: 'publicName', hidden: true},
            {header: '安装位置', width: 120, sortable: true, dataIndex: 'installSite', hidden: true},
            {header: '生产厂家', width: 120, sortable: true, dataIndex: 'manufactoryName', hidden: true},
            {header: '装置类别', width: 80, sortable: true, dataIndex: 'deviceType', hidden: true},
            {header: '装置型号', width: 80, sortable: true, dataIndex: 'model', hidden: true},
            {header: '通信方式', width: 80, sortable: true, dataIndex: 'commTypeName', hidden: true},
            {header: '通信卡号', width: 120, sortable: true, dataIndex: 'mobileNo', hidden: true},
            {header: 'IP地址', width: 120, sortable: true, dataIndex: 'ip', hidden: true},
            {header: '终端编号', width: 80, sortable: true, dataIndex: 'terminalNo', hidden: true},
            {header: '安装日期', width: 80, sortable: true, dataIndex: 'installTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '校验日期', width: 80, sortable: true, dataIndex: 'checkTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '生效日期', width: 80, sortable: true, dataIndex: 'effectTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            //{header: '投运日期', width: 120, sortable: true, dataIndex: 'runTime', xtype: 'datecolumn', format: 'Y-m-d',hidden:true},
            {header: '停用日期', width: 80, sortable: true, dataIndex: 'stopTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '停用原因', width: 80, sortable: true, dataIndex: 'stopReason', hidden: true},
            {header: '有效期', width: 80, sortable: true, dataIndex: 'expireTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '出厂日期', width: 80, sortable: true, dataIndex: 'produceTime', xtype: 'datecolumn', format: 'Y-m-d', hidden: true},
            {header: '端口', width: 80, sortable: true, dataIndex: 'port', hidden: true},
            {header: '唯一码', width: 120, sortable: true, dataIndex: 'uniqueCode', hidden: true},
            {header: '组编码', width: 80, sortable: true, dataIndex: 'zbm', hidden: true},
            {header: '行政区域码', width: 80, sortable: true, dataIndex: 'adminAreaCode', hidden: true},
            {header: '通道', width: 80, sortable: true, dataIndex: 'channel', hidden: true},
            {header: '管理人员', width: 80, sortable: true, dataIndex: 'realName', hidden: true},
            {header: "测点上报状态", dataIndex: 'status', width: 100,
                renderer: function(v, metaData, record, rowIndex, colIndex, store) {
                    var value = Math.floor((parseInt(v) % 1000) / 100);
                    var result = "不上报";
                    if (value > 0) {
                        result = "上报"
                        return result.bold();
                    }
                    return result;
                }
            },
            {header: "日数据上报状态", dataIndex: 'status', width: 100,
                renderer: function(v, metaData, record, rowIndex, colIndex, store) {
                    var value = Math.floor((parseInt(v) % 10000) / 1000);
                    var result = "不上报";
                    if (value > 0) {
                        result = "上报"
                        return result.bold();
                    }
                    return result;
                }
            },
            {header: "月数据上报状态", dataIndex: 'status', width: 80,
                renderer: function(v, metaData, record, rowIndex, colIndex, store) {
                    var value = Math.floor((parseInt(v) % 100000) / 10000);
                    var result = "不上报";
                    if (value > 0) {
                        result = "上报"
                        return result.bold();
                    }
                    return result;
                }
            },
            {header: '上报信息', width: 80, sortable: true, dataIndex: 'uploadMsg'},
            {header: '上报时间', width: 80, sortable: true, dataIndex: 'uploadTime'},
            {header: '备注', id: '备注', width: 80, sortable: true, dataIndex: 'note'}

        ],
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '上报/观测', iconCls: 'icon-upload', handler: report},
            {text: '监测点上报/不上报', iconCls: '', handler: upload, type: 3},
            {text: '日数据上报/不上报', iconCls: '', handler: upload, type: 4},
            {text: '月数据上报/不上报', iconCls: '', handler: upload, type: 5},
            {
                text: '任务上报',
                iconCls: 'icon-linkratio',
                handler: taskUpload
            }
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有" + theme + '信息'
        }),
        listeners: {
            'render': function() {
                tbarPoint.render(this.tbar);
            },
            'rowdblclick': function(thiz, index, e, other) {
                var rs = checkboxSel.getSelections();
                var uploadMsg = rs[0].get("uploadMsg");
                //alert(uploadMsg);
                Ext.getCmp('MsgPanel').html=uploadMsg;
                winUploadMsg.show();
            }
        }
    });
    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);
